const express = require('express')
const formidable = require('formidable')
const advModel = require('../db/model/adv')
const path = require('path')
const route = express.Router()
route.post('/addAdv',(req,res)=>{
    const form = formidable({
        uploadDir:path.resolve(__dirname,'../upload') , //之后的文件存放的地址
        keepExtensions:true  // 是否保存后缀名
    })
    form.parse(req, async (err,params,files)=>{
        console.log(params,'params');
        console.log(files,'files');

        try{
            const findResult =await advModel.find({})
            if(!findResult){
             return res.send({
                 code:10001,
                 msg:'广告信息已经存在',
                 data:null
             })
            }
           
            await advModel.create({
                advTitle:params.advTitle,
                advType:params.advType,
                advOrder:params.advOrder,
                // join方法进行字符串的拼接，将地址拼接完整 
                // path.join('/upload',files.advPic.newFilename) 相当于相对路径中的绝对路径 
                
                advHref:path.join('/upload',files.advPic.newFilename),
                addTime:new Date().toLocaleString()
            })
            res.send({
             code:10000,
             msg:'广告信息添加成功',
             data:findResult
            })
          }catch(e){ 
            console.log('广告信息添加失败'+e.message);
            res.send({
                code:10001,
                msg:'广告信息添加失败'+e.message,
                data:null
            })
          }


    })
  

})

module.exports = route;